<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- alert警告 -->
      <el-alert center show-icon title="注意:只允许为三级分类设置相关参数!" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cate_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="selectedKeysArr"
            expand-trigger="hover"
            :options="cateList"
            :props="cascaderProps"
            @change="categoryChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tap页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTapClick">
        <el-tab-pane label="动态参数" name="many" :disabled="isBtnDisabled">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
          >添加参数</el-button>
          <!-- 添加参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 循环渲染tag标签 模板插槽 用scope接收下这一行的数据-->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 输入文本框  v-if是控制文本框和按钮的切换显示的布尔属性-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="isBtnDisabled">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 模板插槽 用scope接收下这一行的数据-->
              <template slot-scope="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <!-- 输入文本框  v-if是控制文本框和按钮的切换显示的布尔属性-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                ></el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="dialogFormVisible" @close="addDialogClosed">
      <!-- 表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRulesRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogFormVisible"
      @close="editDialogClosed"
    >
      <!-- 表单 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRulesRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cascaderProps: {
        // checkStrictly: true, //可以选择任意一级的选项
        value: 'cat_id', //具体选中的值得属性
        label: 'cat_name', //看到的属性
        children: 'children' //父子嵌套用的哪个属性
      },
      //级联选择框双向绑定到的数组
      selectedKeysArr: [],
      //被激活的页签的名称
      activeName: 'many',
      //动态数据
      manyTableData: [],
      // 静态数据
      onlyTableData: [],
      //添加对话框默认状态
      dialogFormVisible: false,
      //修改对话框的默认状态
      editDialogFormVisible: false,
      //添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      //添加和编辑参数的验证规则对象
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editForm: {
        attr_name: ''
      }
    }
  },
  //生命周期函数
  created() {
    //获取商品分类
    this.getCateList()
  },
  //方法
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败!')
      }
      this.cateList = res.data
      //   console.log(this.cateList)
    },
    // 级联选择器选择改变的时候触发的函数
    categoryChange() {
      // console.log(this.selectedKeysArr)
      this.getParamsData()
    },
    //tap页签点击事件处理函数
    handleTapClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    //获取参数列表数据
    async getParamsData() {
      //只允许显示3级商品分类
      if (this.selectedKeysArr.length !== 3) {
        this.$message.info('只允许操作3级商品分类')
        this.selectedKeysArr =[]
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 根据所选分类的id,和当前所处的面板,获取对应的参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // console.log(res.data)
      //在赋值之前先把attr_vals循环成一个数组
      res.data.forEach(item => {
        //判断数组是不是空,是空就返回一个空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // console.log(item.attr_vals)
        //控制文本框的单独显示与隐藏
        item.inputVisible = false
        //文本框中输入的值
        item.inputValue = ''
      })

      //给对应参数赋值
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    showAddDialog() {
      this.dialogFormVisible = true
    },
    //监听添加对话框的关闭事件,重置表单
    addDialogClosed() {
      this.$refs.addFormRulesRef.resetFields()
    },
    //监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRulesRef.resetFields()
    },
    //确定添加属性按钮
    addParams() {
      //预验证
      this.$refs.addFormRulesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        //关闭对话框
        this.dialogFormVisible = false
        this.getParamsData()
      })
    },
    //显示编辑对话框
    async showEditDialog(attr_id) {
      //点击编辑的时候根据id查询参数
      // console.log(attr_id)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
        params: { attr_sel: this.activeName }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res)
      //把得到的数据放入编辑表单
      this.editForm = res.data
      //显示编辑对话框
      this.editDialogFormVisible = true
    },
    //点击确定修改属性
    editParams() {
      //预验证
      this.$refs.editFormRulesRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editDialogFormVisible = false
        this.getParamsData()
      })
    },
    //根据id删除参数项
    async removeParam(attr_id) {
      //弹框提示
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      //请求删除参数的接口
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      //  console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 点击或者按下enter键都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //如果没有return,则证明输入内容,需要进行后续处理
      //把输入框里的值push到本行attr_vals数组
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      //请求接口,提交参数项
      this.saveAttrVals(row)
    },
    //点击按钮,显示输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点,$nextTick方法的作用,就是当页面重新被渲染之后,才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //tag标签关闭事件
    handleClose(i, row) {
      // console.log(i)
      // console.log(row)
      // splice会修改原数组,可以直接发起请求,删除当前的i项,删除一个
      row.attr_vals.splice(i, 1)
      //请求接口,保存修改
      this.saveAttrVals(row)
    },
    //把对attr_vals的操作保存到数据库
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      return this.$message.success('修改参数项成功')
    }
  },
  //计算属性
  computed: {
    //用数组的长度控制按钮的禁用
    isBtnDisabled() {
      //如果数组的长度不是3,就禁用这个按钮
      if (this.selectedKeysArr.length !== 3) {
        return true
      }
      return false
    },
    //选中的3级分类的id
    cateId() {
      if (this.selectedKeysArr.length === 3) {
        console.log(this.selectedKeysArr[2])
        return this.selectedKeysArr[2]
      }
      return null
    },
    // 动态的对话框表头
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin-top: 15px;
}
.el-input {
  width: 118px;
}
</style>
